using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

namespace LumiSoft.Net.MIME
{
    /// <summary>
    /// Represents MIME entity text/... body. Defined in RFC 2045.
    /// </summary>
    public class MIME_TextBody : MIME_BinaryBody
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null.</exception>
        internal MIME_TextBody(MIME_Entity owner) : base(owner)
        {            
        }


        #region method GetCharset

        /// <summary>
        /// Gets charset from Content-Type. If char set isn't specified, "ascii" is defined as default and it will be returned.
        /// </summary>
        /// <returns>Returns content charset.</returns>
        /// <exception cref="ArgumentException">Is raised when Content-Type has not supported charset parameter value.</exception>
        private Encoding GetCharset()
        {
            if(this.Owner.ContentType == null || string.IsNullOrEmpty(this.Owner.ContentType.Param_CharSet)){
                return Encoding.ASCII;
            }
            else{
                return Encoding.GetEncoding(this.Owner.ContentType.Param_CharSet);
            }
        }

        #endregion


        #region Properties Implementation

        /// <summary>
        /// Gets or sets body text. NOTE: Before getting this value, you must be sure that text data is not very big, 
        /// for example text/xml may be very big.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
        /// <exception cref="ArgumentException">Is raised when Content-Type has not supported charset parameter value.</exception>
        public string Text
        {
            get{ 
                if(this.IsDisposed){
                    throw new ObjectDisposedException(this.GetType().Name);
                }

                return GetCharset().GetString(this.Data); 
            }

            set{
                if(this.IsDisposed){
                    throw new ObjectDisposedException(this.GetType().Name);
                }

                this.SetStream(new MemoryStream(GetCharset().GetBytes(value)),true);
            }
        }

        #endregion

    }
}
